package io.aicn.lowcode.controller;

import io.aicn.lowcode.service.DatabaseSchemaService;
import io.aicn.lowcode.service.MySqlTableGenerationService;
import io.aicn.lowcode.service.SqlExecutionService;
import io.aicn.lowcode.service.SqlParserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;

@Tag(name = "数据库表管理", description = "数据库表结构管理和生成API")
@RestController
@RequestMapping("/api/database")
public class DatabaseTableController {

    @Autowired
    private DatabaseSchemaService databaseSchemaService;

    @Autowired
    private MySqlTableGenerationService mySqlTableGenerationService;

    @Autowired
    private SqlExecutionService sqlExecutionService;
    
    @Autowired
    private SqlParserService sqlParserService;
    
    @Autowired
    private ObjectMapper objectMapper;

    @Operation(summary = "获取数据库模式", description = "获取当前数据库的完整模式信息，包括所有表结构")
    @GetMapping("/schema")
    public Map<String, Object> getDatabaseSchema() {
        return databaseSchemaService.getDatabaseSchema();
    }

    @Operation(summary = "获取数据库模式JSON", description = "获取当前数据库的完整模式信息的JSON格式")
    @GetMapping("/schema/json")
    public String getDatabaseSchemaAsJson() {
        return databaseSchemaService.getDatabaseSchemaAsJson();
    }

    @Operation(summary = "生成建表语句", description = "根据数据库模式JSON生成MySQL8建表语句")
    @PostMapping("/generate-sql")
    public List<String> generateCreateTableStatements(@RequestBody String schemaJson) {
        return mySqlTableGenerationService.generateCreateTableStatements(schemaJson);
    }

    @Operation(summary = "生成带后缀的建表语句", description = "根据数据库模式生成带数字后缀的建表语句")
    @PostMapping("/generate-sql-with-suffix")
    public List<String> generateCreateTableStatementsWithSuffix(@RequestBody String schemaJson, 
                                                                @RequestParam(defaultValue = "1") int suffix) {
        try {
            // 修改表名添加后缀
            String modifiedSchema = addTableSuffix(schemaJson, suffix);
            return mySqlTableGenerationService.generateCreateTableStatements(modifiedSchema);
        } catch (Exception e) {
            throw new RuntimeException("生成建表语句失败: " + e.getMessage());
        }
    }

    @Operation(summary = "执行建表语句", description = "执行建表语句创建新表")
    @PostMapping("/execute-sql")
    public ResponseEntity<Map<String, Object>> executeCreateTableStatements(@RequestBody List<String> sqlStatements) {
        try {
            sqlExecutionService.executeSqlList(sqlStatements);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "SQL执行成功",
                "executedStatements", sqlStatements.size()
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "SQL执行失败: " + e.getMessage(),
                "executedStatements", 0
            ));
        }
    }

    @Operation(summary = "创建表", description = "根据JSON Schema配置创建新表")
    @PostMapping("/tables")
    public ResponseEntity<Map<String, Object>> createTableFromSchema(@RequestBody Map<String, Object> tableSchema) {
        try {
            // 生成SQL语句 - 需要将单个表包装成完整的schema格式
            Map<String, Object> fullSchema = Map.of(
                "databaseInfo", Map.of(
                    "databaseName", "lowcode",
                    "charset", "utf8mb4",
                    "collation", "utf8mb4_unicode_ci",
                    "engine", "InnoDB"
                ),
                "tables", List.of(tableSchema)
            );
            String schemaJson = mapToJson(fullSchema);
            List<String> sqlStatements = mySqlTableGenerationService.generateCreateTableStatements(schemaJson);
            
            // 执行SQL语句
            sqlExecutionService.executeSqlList(sqlStatements);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "表创建成功",
                "tableName", tableSchema.get("tableName"),
                "sqlStatements", sqlStatements
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "表创建失败: " + e.getMessage()
            ));
        }
    }

    @Operation(summary = "获取所有表名", description = "获取数据库中所有表的名称")
    @GetMapping("/tables")
    public ResponseEntity<List<String>> getTableNames() {
        return ResponseEntity.ok(sqlExecutionService.getTableNames());
    }

    @Operation(summary = "获取表结构", description = "获取指定表的结构信息")
    @GetMapping("/tables/{tableName}/schema")
    public ResponseEntity<List<Map<String, Object>>> getTableSchema(@PathVariable String tableName) {
        return ResponseEntity.ok(sqlExecutionService.getTableSchema(tableName));
    }

    @Operation(summary = "导入SQL建表语句", description = "解析CREATE TABLE语句并创建表")
    @PostMapping("/import-sql")
    public ResponseEntity<Map<String, Object>> importTableFromSql(@RequestBody Map<String, String> request) {
        try {
            String createTableSql = request.get("sql");
            if (createTableSql == null || createTableSql.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "SQL语句不能为空"
                ));
            }

            // 解析SQL语句
            Map<String, Object> tableSchema = sqlParserService.parseCreateTableSql(createTableSql);
            
            // 生成标准的建表语句
            Map<String, Object> fullSchema = Map.of(
                "databaseInfo", Map.of(
                    "databaseName", "lowcode",
                    "charset", "utf8mb4",
                    "collation", "utf8mb4_unicode_ci",
                    "engine", "InnoDB"
                ),
                "tables", List.of(tableSchema)
            );
            String schemaJson = mapToJson(fullSchema);
            List<String> sqlStatements = mySqlTableGenerationService.generateCreateTableStatements(schemaJson);
            
            // 执行SQL语句
            sqlExecutionService.executeSqlList(sqlStatements);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "表导入成功",
                "tableName", tableSchema.get("tableName"),
                "parsedSchema", tableSchema,
                "generatedSql", sqlStatements
            ));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "表导入失败: " + e.getMessage()
            ));
        }
    }

    @Operation(summary = "解析SQL建表语句", description = "仅解析CREATE TABLE语句，不执行创建操作")
    @PostMapping("/parse-sql")
    public ResponseEntity<Map<String, Object>> parseTableSql(@RequestBody Map<String, String> request) {
        try {
            String createTableSql = request.get("sql");
            if (createTableSql == null || createTableSql.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "SQL语句不能为空"
                ));
            }

            // 解析SQL语句
            Map<String, Object> tableSchema = sqlParserService.parseCreateTableSql(createTableSql);
            
            // 生成预览SQL
            Map<String, Object> fullSchema = Map.of(
                "databaseInfo", Map.of(
                    "databaseName", "lowcode",
                    "charset", "utf8mb4",
                    "collation", "utf8mb4_unicode_ci",
                    "engine", "InnoDB"
                ),
                "tables", List.of(tableSchema)
            );
            String schemaJson = mapToJson(fullSchema);
            List<String> sqlStatements = mySqlTableGenerationService.generateCreateTableStatements(schemaJson);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "SQL解析成功",
                "tableName", tableSchema.get("tableName"),
                "parsedSchema", tableSchema,
                "previewSql", sqlStatements
            ));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "SQL解析失败: " + e.getMessage()
            ));
        }
    }

    private String addTableSuffix(String schemaJson, int suffix) throws Exception {
        // 简单的JSON处理，实际应用中应该使用更完善的JSON处理库
        return schemaJson.replaceAll("\"tableName\":\"([^\"]+)\"", "\"tableName\":\"$1_" + suffix + "\"");
    }
    
    private String mapToJson(Map<String, Object> map) {
        try {
            return objectMapper.writeValueAsString(map);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert map to JSON", e);
        }
    }
}